//
//  FJSetUpInfoViewController.swift
//  FruitJuice
//
//  Created by Rui on 2023/12/16.
//

import UIKit
import ZLPhotoBrowser

class FJSetUpInfoViewController: FJBaseViewController {

    private let backView            = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("FJ_SignIn_InfoBg").end()
    private let titleLabel          = c_make_ex(UILabel.self)
        .color(.white).font(31.font_bold)
        .alignment(.center).text("About You").end()
    private let backButton          = c_make_ex(UIButton.self)
        .image("FJ_SignIn_Info_back").end()
    private let nameTextF           = c_make_ex(UITextField.self)
        .bgColor(.black.alpha(0.4)).corner(25).font(17.font_medium)
        .placeholder("Enter your nickname").color(.white).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let avatarLabel         = c_make_ex(UILabel.self)
        .color(.white).font(21.font_bold).text("Avatar").end()
    private let doneButton          = c_make_ex(UIButton.self)
        .bgColor("#FF9133".toColor).corner(25).font(21.font_bold)
        .text("DONE").color(.white).end()
    private let skipButton          = c_make_ex(UIButton.self)
        .text("Skip").color(.clear).color(.white).font(21.font_bold).end()
    
    private var dataSource: [FJSetupInfoModel] = [
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemOne",select: false,isShowCamera: true),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemTwo",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemThree",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemFour",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemFive",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemSix",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemSeven",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemEight",select: false,isShowCamera: false),
    FJSetupInfoModel(icon: "FJ_SignIn_Info_itemNine",select: false,isShowCamera: false)]
    
    private var selImg: UIImage?
    private var imgUrl: String?
    private var selIndex: Int?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigation.bar.isHidden = true
        view.subviews{
            backView.subviews{
                backButton
                titleLabel
                nameTextF
                collectionView
                avatarLabel
                doneButton
                skipButton
            }
        }
        
        let itemW = (.screenWidth - 55.0)/3
        
        backView.fillContainer()
        backButton.top(.statusHeight + 7).leading(15).size(30)
        titleLabel.centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        nameTextF.width(320).height(50).centerHorizontally()
        nameTextF.Top == backButton.Bottom + 44.0
        collectionView.leading(0).trailing(0).height(itemW*3 + 30)
        collectionView.Top == nameTextF.Bottom + 30.0
        avatarLabel.leading(40)
        avatarLabel.Top == collectionView.Bottom + 15.0
        doneButton.width(320).height(50).centerHorizontally()
        doneButton.Top == collectionView.Bottom + 90.0
        skipButton.width(320).height(50).centerHorizontally()
        skipButton.Top == doneButton.Bottom + 5
        
        backView.isUserInteractionEnabled = true
        nameTextF.style { v in
            v.placehold("#B5B5B5".toColor, font: 17.font_medium)
            let leftImage = UIImageView(image: UIImage(named: "FJ_SignIn_Info_avatar"))
            leftImage.frame = CGRect(x: 15, y: 13, width: 24, height: 24)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            leftV.addSubview(leftImage)
            v.leftView = leftV
            v.leftViewMode = .always
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.5, bottom: 0, right: 12.5)
        layout.scrollDirection = .vertical
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJAboutYouCollectionItem.self, forCellWithReuseIdentifier: FJAboutYouCollectionItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        doneButton.addTarget(self, action: #selector(clickDoneButton), for: .touchUpInside)
        skipButton.addTarget(self, action: #selector(clickSkipButton), for: .touchUpInside)
    }
}

extension FJSetUpInfoViewController: UICollectionViewDelegate,UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJAboutYouCollectionItem.description(), for: indexPath) as? FJAboutYouCollectionItem else { return UICollectionViewCell() }
        item.itemModel = dataSource[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        selIndex = indexPath.row
        if indexPath.row == 0 {
            //打开相册
            ZLPhotoConfiguration.default()
                .allowSelectVideo(false)
            let ps = ZLPhotoPreviewSheet()
            ps.selectImageBlock = { [weak self] results, isOriginal in
                ToastTool.show()
                let image = results.first?.image
                self?.selImg = image
                var models = [FJSetupInfoModel]()
                self?.dataSource.forEach { model in
                    var itemModel = model
                    models.append(itemModel)
                }
                if let img = image {
                    models[0].image = img
                }
                self?.dataSource = models
                collectionView.reloadData()
                RT.uploadCoverImage(file: (self?.imageToBase64String(image: image!))!) { [weak self] (dict) in
                    ToastTool.dismiss()
                    self?.imgUrl = dict.url!
                }
            }
            ps.showPhotoLibrary(sender: self)
        }
        
        var models = [FJSetupInfoModel]()
        dataSource.forEach { model in
            var itemModel = model
            itemModel.select = false
            models.append(itemModel)
        }
        models[indexPath.row].select = true
        if let img = selImg {
            models[0].image = img
        }
        dataSource = models
        collectionView.reloadData()
    }
}


//MARK: action
extension FJSetUpInfoViewController {
    
    @objc private func clickBackButton(){
        
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickDoneButton(){
        
        guard let index = selIndex else {
            "Please upload photo.".toast_error
            return
        }
        guard let name = nameTextF.text, name.count > 0 else {
            "Please enter your username.".toast_error
            return
        }
        ToastTool.show()
        if index != 0 {
            let model = dataSource[index]
            let image = UIImage(named: model.icon)
            RT.uploadCoverImage(file: (self.imageToBase64String(image: image!))!) { dict in
                let img = dict.url!
                let dict = ["headImage":img,"name":name,"userId":USEINFOMODEL.id]
                RT.initUserInfoWith(paraInfo: dict as [String : Any]) { info in
                    ToastTool.dismiss()
                    UIApplication.window?.rootViewController = FJNavViewController(rootViewController:  FJHomeViewController())
                }
            }
        }else{
            
            if let img = imgUrl {
                let dict = ["headImage":img,"name":name,"userId":USEINFOMODEL.id]
                RT.initUserInfoWith(paraInfo: dict as [String : Any]) { info in
                    ToastTool.dismiss()
                    UIApplication.window?.rootViewController = FJNavViewController(rootViewController:  FJHomeViewController())
                }
            }else {
                clickSkipButton()
            }
        }
    }
    
    @objc private func clickSkipButton(){
        
        ToastTool.show()
        let image = UIImage(named: "FJ_Common_avator")
        RT.uploadCoverImage(file: (self.imageToBase64String(image: image!))!) { dict in
            let imgUrl = dict.url!
            let dict = ["headImage":imgUrl,"userId":USEINFOMODEL.id,"name":"FruitJuice"]
            RT.initUserInfoWith(paraInfo: dict as [String : Any]) { info in
                UIApplication.window?.rootViewController = FJNavViewController(rootViewController:  FJHomeViewController())
            }
        }
    }
}

class FJAboutYouCollectionItem: UICollectionViewCell {
    
    private let mainView = c_make_ex(UIImageView.self)
        .corner((.screenWidth - 55.0)/6.0).end()
    private let shadowV  = c_make_ex(UIView.self)
        .bgColor("#FF9133".toColor.alpha(0.25))
        .corner((.screenWidth - 55.0)/6.0).end()
    private let cameraImg = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("FJ_SignIn_Info_camera").end()
    
    var itemModel: FJSetupInfoModel? {
        didSet{
            guard let md = itemModel else { return }
            mainView.image = md.icon.toImage
            if let img = md.image {
                mainView.image = img
            }
            shadowV.isHidden = !md.select
            cameraImg.isHidden = !md.isShowCamera
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.subviews {
            mainView.subviews{
                shadowV
            }
            cameraImg
        }

        mainView.fillContainer()
        shadowV.fillContainer()
        cameraImg.trailing(0).bottom(0).size(40)
//        let itemW = (.screenWidth - 55.0)/6.0
//        mainView.layer.cornerRadius = itemW/2.0
//        shadowV.layer.cornerRadius = itemW/2.0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
